<template>
    <div class="app-container" v-loading="mtloading" ref="refMGoods">
        <el-form-item  :label="$t('goods.ctrips.isOpen')" class="w-1/2">
            <el-switch v-model="isgmGoods" />
        </el-form-item>
        <div v-if="isgmGoods">
            <!-- 指定酒店 -->
            <el-form-item :label="$t('goods.ctrips.assignHotel')+':'" prop="designated_goods" class="w-1/2">
                <el-radio-group v-model="data.infoHotel.hotels" @change="changehotels">
                    <el-radio :label="1" border>{{$t('goods.ctrips.all')}}</el-radio>
                    <el-radio :label="2" border>{{$t('goods.ctrips.specify')}}</el-radio>
                    <el-radio :label="3" border>{{$t('goods.ctrips.exclud')}}</el-radio>
                </el-radio-group>
                <el-icon class="ml-2" @click="addHotel" v-if="data.infoHotel.hotels == 2 || data.infoHotel.hotels == 3"
                    :size="20">
                    <CirclePlus />
                </el-icon>
            </el-form-item>
            <el-form-item>
                <el-form :model="data.infoHotel" class="w-full" label-width="120">
                    <el-form-item v-if="data.infoHotel.hotels == 2 || data.infoHotel.hotels == 3">
                        <el-table border :data="hotelList" :header-cell-style="{ 'text-align': 'center' }"
                            :cell-style="{ 'text-align': 'center' }" class="w-full mr-5">
                            <el-table-column prop="c_id" :label="$t('goods.ctrips.city')">
                                <template #default="scope">
                                    <el-select v-model="scope.row.cityId" @change="changeCity" :placeholder="$t('message.pleaseSelect')"
                                        v-if="!list.hotelList || scope.row.isAdd">
                                        <el-option v-for="item in cityList" :key="item.cityId" :label="item.cityName"
                                            :value="item.cityId" />
                                    </el-select>
                                    <span v-else>{{ setCity(scope.row) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="hotelName" :label="$t('goods.ctrips.hotel')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-select v-if="!list.hotelList || scope.row.isAdd" v-model="scope.row.hotelId"
                                        @change="changeHotel(scope.row)" :placeholder="$t('message.pleaseSelect')" clearable filterable
                                        :loading="mtloading">
                                        <el-option v-for="item in HotelList" :key="item.hotelId" :label="item.hotelName"
                                            :value="item.hotelId" />
                                    </el-select>
                                    <span v-else>{{ scope.row.hotelName }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('public.picture')" show-overflow-tooltip>
                                <template #default="scope">
                                    <img v-if="scope.row.imageUrl" class="w-24 h-24 inline-block"
                                        :src="scope.row.imageUrl" />
                                    <span v-else></span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="hotelTel" :label="$t('goods.ctrips.phone')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="!list.hotelList || scope.row.isAdd || scope.row.isEdit"
                                        v-model.number="scope.row.hotelTel" :placeholder="$t('goods.ctrips.tel')" clearable />
                                    <span v-else>{{ scope.row.hotelTel }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="roomQuantity" :label="$t('goods.ctrips.rooms')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="!list.hotelList || scope.row.isAdd || scope.row.isEdit"
                                        v-model.number="scope.row.roomQuantity" :placeholder="$t('goods.groupM.pleaseRooms')" clearable />
                                    <span v-else>{{ scope.row.roomQuantity }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="rise_fall_ratio" :label="$('goods.ctrips.ratio')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.rise_fall_ratio" controls-position="right"
                                        v-if="!list.hotelList || scope.row.isAdd || scope.row.isEdit">
                                        <template #decrease-icon>
                                            <el-icon>
                                                <Minus />
                                            </el-icon>
                                        </template>
                                    </el-input-number>
                                    <span v-else>{{ scope.row.rise_fall_ratio }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('public.operate')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-button size="small" type="primary" v-if="!scope.row.isAdd"
                                        @click="edit(scope.row)" v-prmis="'free_hotel_update'">{{$t('public.edit')}}</el-button>
                                    <el-button size="small" type="primary"
                                        @click="delHotel(scope.row, scope.$index)"  v-prmis="'free_hotel_del'">{{ $t('public.del')}}</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <!-- 指定商品 -->
            <el-form-item :label="$t('goods.groupM.designatedGood')+':'" prop="designated_goods" class="w-1/2">
                <el-radio-group v-model="data.infoGoods.hotels">
                    <el-radio :label="1" border>{{$t('goods.ctrips.all')}}</el-radio>
                    <el-radio :label="2" border>{{$t('goods.ctrips.specify')}}</el-radio>
                    <el-radio :label="3" border>{{$t('goods.ctrips.exclud')}}</el-radio>
                </el-radio-group>
                <el-icon class="ml-2" @click="addGoods" v-if="data.infoGoods.hotels == 2 || data.infoGoods.hotels == 3"
                    :size="20">
                    <CirclePlus />
                </el-icon>
            </el-form-item>
            <el-form-item>
                <el-form :model="data.infoGoods" class="w-full" label-width="120">
                    <el-form-item v-if="data.infoGoods.hotels == 2 || data.infoGoods.hotels == 3">
                        <el-table border :data="gList" :header-cell-style="{ 'text-align': 'center' }"
                            :cell-style="{ 'text-align': 'center' }" class="w-full mr-5"
                            :default-sort="{ prop: 'date', order: 'descending' }">
                            <el-table-column prop="g_name" :label="$t('machine.goods.name')">
                                <template #default="scope">
                                    <el-select v-if="!list.goodsList || scope.row.isAdd" v-model="scope.row.g_id"
                                        :placeholder="$t('message.pleaseSelect')" clearable filterable @change="changeGoods(scope.row)">
                                        <el-option v-for="item in goodsList" :key="item.gc_id"
                                            :label="item.g_id + '-' + item.g_name" :value="item.g_id" />
                                    </el-select>
                                    <span class="cursor-pointer" v-else>{{ setgName(scope.row) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="pic" :label="$t('machine.goods.pic')" show-overflow-tooltip>
                                <template #default="scope">
                                    <img v-if="scope.row.pic" class="w-24 h-24 inline-block" :src="scope.row.pic" />
                                    <span v-else></span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="g_type" :label="$t('machine.goods.type')" show-overflow-tooltip>
                                <template #default="scope">
                                    {{ scope.row.g_type == 1 ? $t('goods.groupM.normalGood') : scope.row.g_type == 3 ? $t('goods.groupM.ticket') : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="sku" label="SKU" show-overflow-tooltip />
                            <el-table-column :label="$t('machine.goods.sellingPrice')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input-number v-if="!list.goodsList || scope.row.isAdd || scope.row.isEdit"
                                        v-model="scope.row.sale_amount" controls-position="right">
                                        <template #decrease-icon>
                                            <el-icon>
                                                <Minus />
                                            </el-icon>
                                        </template>
                                    </el-input-number>
                                    <span v-else>{{ scope.row.sale_amount }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('goods.ctrips.ratio')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input-number v-if="!list.goodsList || scope.row.isAdd || scope.row.isEdit"
                                        v-model="scope.row.rise_fall_ratio" controls-position="right">
                                        <template #decrease-icon>
                                            <el-icon>
                                                <Minus />
                                            </el-icon>
                                        </template>
                                    </el-input-number>
                                    <span v-else>{{ scope.row.rise_fall_ratio }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('public.operate')" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-button size="small" type="primary" @click="edit(scope.row)"
                                        v-if="!scope.row.isAdd" v-prmis="'free_goods_update'">{{$t('public.edit')}}</el-button>
                                    <el-button size="small" type="primary"
                                        @click="delGoods(scope.row, scope.$index)" v-prmis="'free_goods_del'">{{ $t('public.del')}}</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item v-if="isSaveAll" :label="$('goods.ctrips.ratio')+':'" class="w-1/2">
                <el-input v-model.number="data.rise" :placeholder="$t('goods.groupM.pleaseRatio')" clearable />
            </el-form-item>
            <div class="inline-block">
                <el-button type="primary" @click="saveAll()" v-prmis="'machine_free_update' || 'machine_free_add'">{{$t('goods.groupM.saveAll')}}</el-button>
                <el-button type="primary" @click="delAll" v-prmis="'free_goods_del'"> {{$t('goods.groupM.delAll')}} </el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n' 
const { t: $t } = useI18n()
import { useRoute } from "vue-router";
import { getFindFree, freeDel, freeUpdate, getCityList, getHotelList, freeHotelUpdate, freeHotelAdd, freeHotelDel, freeGoodsDel, freeGoodsAdd, freeAdd, freeGoodsUpdate } from '@/api/machine_gmGoods'
import { ElMessage, ElMessageBox } from "element-plus";
import { getgoodsList } from "@/api/goods";
import { onMounted, computed, inject } from "vue";
let props = defineProps({
    info: {
        type: Object,
        default: {}
    }
})
let refMGoods = ref()
const route = useRoute()
let mtloading = ref(false) // 加载
let isgmGoods = ref(false)
let isunEdit = ref(false)
let isEdit = ref(false)
let hotelList = ref([{
    isAdd: true,
    cityId: '',
    hotelId: '',
    hotelName: '',
    hotelTel: '',
    imageUrl: '',
    roomQuantity: null,
    rise_fall_ratio: 0
}])
let gList = ref([{
    isAdd: true,
    g_id: '',
    sku: '',
    g_type: null,
    sale_amount: '',
    rise_fall_ratio: 0,
    pic: ''
}])
let data = reactive({
    rise: '0',
    infoHotel: {
        designated_machine: 1,
        hotels: 1,
        exclusion: true
    },
    infoGoods: {
        designated_machine: 1,
        hotels: 1,
        exclusion: true
    },
    isTable: false,
})
const goodsList = ref([])
let list = ref({})
interface ListItem {
    cityId: string
    cityName: string
}
const emit = defineEmits(['gmInject'])
const cityList = ref<ListItem[]>([])
const HotelList = ref<ListItem[]>([])
let isSaveAll = computed(() => {
    return data.infoGoods.hotels == 1 || data.infoHotel.hotels == 1
})
// 获取城市列表
let getCity = () => {
    getCityList({}).then(res => {
        if (res.state == 200) {
            cityList.value = res.data.city
        }
    })
}
getCity()
let setCity = (row: any) => {
    let name = '--'
    for (const item of cityList.value) {
        if (item.cityId === row.cityId) {
            name = item.cityName
            break;
        }
    }
    return name
}
let setgName = (row: any) => {
    for (const item of goodsList.value) {
        if (row.g_id == item.g_id) {
            row.g_name = item.g_name
        }
    }
    return row.g_name || '--'
}
// 获取商品列表
let findgoodsList = () => {
    getgoodsList({}).then(res => {
        if (res.state == 200) {
            goodsList.value = res.data.filter(item => item.g_type != 2)
        }
    })
}
findgoodsList()
// 改变酒店下拉
let changeHotel = (row: number) => {
    for (let item of HotelList.value) {
        if (item.hotelId == row.hotelId) {
            row.imageUrl = item.imageUrl
            break;
        }
    }
}
// 改变城市下拉
let changeCity = (val: number) => {
    let parm = {
        page: 1,
        pageNum: 15,
        cityId: val
    }
    getHotelList(parm).then(res => {
        if (res.state == 200) {
            HotelList.value = res.data.list
        }
    })
}
// 改变商品名称下拉
let changeGoods = (row: any) => {
    for (let item of goodsList.value) {
        if (item.g_id == row.g_id) {
            row.pic = item.pic
            row.g_type = item.g_type
            row.sku = item.sku
            row.sale_amount = item.retail_price
            break;
        }
    }
}
onMounted(() => {
    getList()
})
// 获取组合商品配置列表
let getList = () => {
    let info = JSON.parse(decodeURI(route.query.l))
    mtloading.value = true
    getFindFree({ m_id: info.id }).then(res => {
        mtloading.value = false
        if (res.data) {
            list.value = res.data
            isgmGoods.value = list.value.free_status == 1 ? true : false
            data.infoGoods.hotels = list.value.designated_goods
            data.infoHotel.hotels = list.value.designated_hotel
            hotelList.value = list.value.hotelList ? list.value.hotelList : hotelList.value
            data.rise = list.value.rise_fall_ratio
            if (list.value.goodsList && list.value.goodsList.length) {
                gList.value = list.value.goodsList.filter(item => item.g_type != 2)
            }
        }

    })
}
// 删除酒店
const delHotel = (row: any, index: number) => {
    if (row.mfh_id) {
        freeHotelDel({ mfh_id: row.mfh_id }).then(res => {
            if (res.state == 200) {
                ElMessage({
                    message: $t('message.delSuccess'),
                    type: 'success'
                })

                getList()
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    } else {
        hotelList.value.splice(index, 1)
    }
}
// 添加酒店
let addHotel = () => {
    isEdit.value = false
    const now = new Date()
    now.setDate(now.getDate() + 1)
    hotelList.value.push({
        isAdd: true,
        hotelName: '',
        hotelTel: '',
        imageUrl: '',
        roomQuantity: null,
        rise_fall_ratio: 0
    })
}
// 删除商品
const delGoods = (row: any, index: number) => {
    if (row.mfg_id) {
        freeGoodsDel({ mfg_id: row.mfg_id }).then(res => {
            if (res.state == 200) {
                ElMessage({
                    message: $t('message.delSuccess'),
                    type: 'success'
                })
                getList()
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    } else {
        gList.value.splice(index, 1)
    }
}
// 添加商品
let addGoods = () => {
    isEdit.value = false
    const now = new Date()
    now.setDate(now.getDate() + 1)
    gList.value.push({
        isAdd: true,
        g_id: '',
        sku: '',
        g_name: '',
        g_type: null,
        sale_amount: 0,
        rise_fall_ratio: 0,
    })
}
let onSaveHotel = (row: any) => {
    if (row.mfh_id) {
        let pram = {
            mfh_id: row.mfh_id,
            hotelTel: row.hotelTel,
            imageUrl: row.imageUrl,
            roomQuantity: row.roomQuantity,
            rise_fall_ratio: row.rise_fall_ratio
        }
        freeHotelUpdate(pram).then(res => {
            if (res.state == 200) {
                isEdit.value = false
                ElMessage({
                    message: $t('message.modifySuccess'),
                    type: 'success'
                })
                isunEdit.value = false
                getList()
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    } else {
        let arr = cityList.value.filter(item => item.cityId == row.cityId)
        let arrHotel = HotelList.value.filter(item => item.hotelId == row.hotelId)
        let pram = {
            mf_id: list.value.mf_id,
            cityId: row.cityId,
            tc_id: arr[0].tc_id,
            hotelId: row.hotelId,
            hotelName: arrHotel[0].hotelName
        }
        if (row.hotelTel) {
            pram.hotelTel = row.hotelTel
        }
        if (row.imageUrl) {
            pram.imageUrl = row.imageUrl
        }
        if (row.roomQuantity) {
            pram.roomQuantity = row.roomQuantity
        }
        if (row.rise_fall_ratio) {
            pram.rise_fall_ratio = row.rise_fall_ratio
        }
        if (!pram.mf_id || !pram.cityId || !pram.cityId || !pram.hotelId || !pram.hotelName) {
            return ElMessage({
                message:  $t('message.pleaseFill'),
                type: 'error'
            })
        }
        freeHotelAdd(pram).then(res => {
            if (res.state == 200) {
                isEdit.value = false
                ElMessage({
                    message: $t('message.addSuccess'),
                    type: 'success'
                })
                // getList()
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    }
}
let saveGoods = (row: any) => {
    if (row.mfg_id) {
        let pram = {
            mfg_id: row.mfg_id,
            hotelTel: row.hotelTel,
            imageUrl: row.imageUrl,
            roomQuantity: row.roomQuantity,
            rise_fall_ratio: row.rise_fall_ratio
        }
        freeGoodsUpdate(pram).then(res => {
            if (res.state == 200) {
                isEdit.value = false
                ElMessage({
                    message: $t('message.modifySuccess'),
                    type: 'success'
                })
                isunEdit.value = false
                row.isEdit = false
                row.isAdd = false
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    } else {
        let pram = {
            mf_id: list.value.mf_id,
            g_id: row.g_id,
            sale_amount: row.sale_amount
        }
        if (row.rise_fall_ratio) {
            pram.rise_fall_ratio = row.rise_fall_ratio
        }
        if (!pram.mf_id || !pram.g_id) {
            return ElMessage({
                message:  $t('message.pleaseFill'),
                type: 'error'
            })
        }
        freeGoodsAdd(pram).then(res => {
            if (res.state == 200) {
                isEdit.value = false
                ElMessage({
                    message: $t('message.addSuccess'),
                    type: 'success'
                })
                getList()
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    }
}
let cancel = (row: any) => {
    row.isEdit = false
    row.isAdd = false
}
let edit = (row: any) => {
    if (!row.isAdd) {
        row.isEdit = true
    } else {
        row.isAdd = false
    }

}
// 删除全部
let delAll = () => {
    let info = JSON.parse(decodeURI(route.query.l))
    ElMessageBox.confirm($t('message.isTip'))
        .then(res => {
            freeDel({ m_id: info.id, mf_id: list.value.mf_id }).then(res => {
                if (res.state == 200) {
                    ElMessage({
                        message: $t('message.delSuccess'),
                        type: 'success'

                    })
                    emit('gmInject')
                    return
                }
                ElMessage({
                    message: $t('message.networkFailed'),
                    type: 'error'
                })
            })


        }).catch(err => {
            console.log('取消')
        })
}
// 添加全部
let setAddAll = () => {
    let info = JSON.parse(decodeURI(route.query.l))
    let parm = {
        m_id: info.id + '',
        machine_id: props.info.machine_id,
        machine_name: props.info.machine_name,
        free_status: isgmGoods.value ? '1' : '2',
        designated_hotel: data.infoHotel.hotels + '',
        designated_goods: data.infoGoods.hotels + '',
    }
    if (gList.value.length && data.infoGoods.hotels != 1) {
        parm.goodsList = gList.value
    }
    if (data.rise) {
        parm.rise_fall_ratio = data.rise
    }
    //指定酒店
    if (data.infoHotel.hotels != 1) {
        if (hotelList.value && hotelList.value.length && !list.value.hotelList) {
            hotelList.value.forEach(items => {
                let hotel = HotelList.value.filter(item => items.hotelId == item.hotelId)
                let arr = cityList.value.filter(item => items.cityId == item.cityId)
                items.tc_id = arr[0].tc_id
                items.hotelName = hotel[0].hotelName
            })
            parm.hotelList = hotelList.value
        }
    }

    freeAdd(parm).then(res => {
        if (res.state == 200) {
            ElMessage({
                message: $t('message.addSuccess'),
                type: 'success'
            })
            getList()
            return
        }
        ElMessage({
            message: $t('message.networkFailed'),
            type: 'error'
        })
    })
}
// 更新全部
let setUpdataAll = () => {
    let parm = {
        mf_id: list.value.mf_id,
        free_status: isgmGoods.value ? '1' : '2'
    }
    // 指定为全部时
    if (data.rise) {
        parm.rise_fall_ratio = data.rise
    }
    if (data.infoHotel.hotels) {
        parm.designated_hotel = data.infoHotel.hotels + ''
    }
    if (data.infoGoods.hotels) {
        parm.designated_goods = data.infoGoods.hotels + ''
    }

    /* 指定为指定除外.指定列表 */
    // 酒店
    if (data.infoHotel.hotels == 1 && list.value.hotelList) {
        let delHotel = []
        list.value.hotelList.forEach(item => {
            delHotel.push(item.mfh_id)
        })
        parm.delHotel = delHotel.join(',')
    }
    // 商品
    if (data.infoGoods.hotels == 1 && list.value.goodsList) {
        let delGoods = []
        list.value.goodsList.forEach(item => {
            delGoods.push(item.mfg_id)
        })
        parm.delGoods = delGoods.join(',')
    }
    // 新增酒店时
    if (hotelList.value && data.infoHotel.hotels != 1) {
        hotelList.value.forEach(items => {
            let arr = cityList.value.filter(item => items.cityId == item.cityId)
            let arrHotel = HotelList.value.filter(item => item.hotelId == items.hotelId)
            items.tc_id = arr[0].tc_id
            items.hotelName = arrHotel.length ? arrHotel[0].hotelName : ''
        })
        parm.hotelList = hotelList.value
    }
    // 商品
    if (gList.value.length && data.infoGoods.hotels != 1) {
        parm.goodsList = gList.value
        let arr = []
        parm.goodsList.forEach(item => {
            arr.push({
                rise_fall_ratio: item.rise_fall_ratio,
                sale_amount: item.sale_amount,
                g_id: item.g_id,
                mfg_id: item.mfg_id
            })
        })
        parm.goodsList = arr
    }
    freeUpdate(parm).then(res => {
        if (res.state == 200) {
            ElMessage({
                message: $t('message.modifySuccess'),
                type: 'success'
            })
            getList()
            return
        }
        ElMessage({
            message: $t('message.networkFailed'),
            type: 'error'
        })
    })
}
// 保存全部
let saveAll = () => {
    // 酒店
    if (data.infoHotel.hotels != 1 || data.infoGoods.hotels != 1) {
        // 指定非全部是必传
        let arrHotel = hotelList.value.filter(item => !item.cityId)
        if (list.value && data.infoHotel.hotels != 1 && arrHotel.length) {
            return ElMessage({
                message: $t('message.noAddHotel'),
                type: 'error'
            })
        }
        let arrGoods = gList.value.filter(item => !item.g_id)
        if (list.value && data.infoGoods.hotels != 1 && arrGoods.length) {
            return ElMessage({
                message: $t('message.noAddGoods'),
                type: 'error'
            })
        }
        if (list.value.mf_id) {
            setUpdataAll()
        } else {
            setAddAll()
        }
    } else {
        if (!list.value.mf_id) {
            setAddAll()
            return
        } else {
            setUpdataAll()
        }
    }
}
</script>
<style type="text/css">
.dashed {
    border: 2px dashed var(--el-border-color);
}

.el-icon-delete {
    text-align: center;
    margin: auto;
}
</style>